// pages/homePage/homePage.js
// 个人主页
Page({

  /**
   * 页面的初始数据
   */
  data: {
    adopt: false,
    personMsgList: {},
    indicatorDots: true,
    autoplay: true,
    zhezhao: false,
    shouquanWindow: false,
    passwordVerificationWindow: false,
    contactMsgWindow: false,
    labelWindow: false,
    labelFormWindow: false,
    interval: 5000,
    duration: 1000,
    homePageBottomBtnText: '查看价格、联系方式',
    eyeCloseIcon: '/assets/icons/eye-close.png',
    eyeOpenIcon: '/assets/icons/eye-open.png',
    eyeSwitch: false,
    phone: null,
    price: null,
    navId: null,
    labelValue: [],
    passwordValue: '',
    productId: null,
    labelItemLength: 3,
    labelItemCount: 3,
    projectList: [],
    projectIdx: 0,
    calendarWindow: false,
    year: '',
    month: '',
    calendarGroup: []
  },
  calcScheduling: function() {
    // 计算日历排期显示
    let that = this
    let curDate = new Date()
    let y = curDate.getFullYear()
    let m = curDate.getMonth() + 1
    let time = y + '-' + m
    let config = wx.getStorageSync('config')
    let productId = that.data.personMsgList.id
    that.setData({
      year: y,
      month: m
    })

    wx.request({
      url: config.host + 'api/chiCkInTime/checkInTime?date=' + time + '&productId=' + productId,
      method: 'GET',
      success(res) {
        if (res.data.status == 200) {
          let data = res.data.data
          let dayArray = []
          for (let i = 0; i < data.length; i++) {
            let s = data[i].split('-')[2]
            dayArray.push(s)
          }
          // 已排期日期
          let calendarSche = []
          for (let i = 0; i < dayArray.length; i++) {
            let obj = {
              month: 'current',
              day: dayArray[i],
              color: '#117FF2',
              background: '#D2E5F9'
            }
            calendarSche.push(obj)
          }
          // console.log('已排期日', dayArray)
          // 当天日期
          let today = String(new Date().getDate())
          let todayArr = []
          let todayObj = {
            month: 'current',
            day: today,
            color: '#fff',
            background: '#1D2088'
          }
          todayArr.push(todayObj)
          // 空挡日期
          curDate.setMonth(m)
          curDate.setDate(0)
          let currentDays = curDate.getDate()
          let curTotalDays = []
          let j = 1
          for (let i = 0; i < currentDays; i++) {
            curTotalDays[i] = String(j < 10 ? '0' + j : j)
            j++
          }
          // console.log('当月总天数', curTotalDays)
          let neutralDays = curTotalDays.concat(dayArray).filter((val, index, arr) => {
            return arr.indexOf(val) === arr.lastIndexOf(val)
          })
          // console.log('空档日', neutralDays)
          let calendarNeutral = []
          for (let i = 0; i < neutralDays.length; i++) {
            let obj = {
              month: 'current',
              day: neutralDays[i],
              color: '#FD3347',
              background: '#FFE2E5'
            }
            calendarNeutral.push(obj)
          }

          that.setData({
            calendarGroup: calendarSche.concat(calendarNeutral).concat(todayArr)
          })
        }
      }
    })
  },
  changeInput: function(e) {
    // 双向绑定-添加标签，密码验证
    let dataset = e.currentTarget.dataset
    let value = e.detail.value
    this.data[dataset.obj] = value.replace(/\s*/g, "")
    this.setData({
      obj: this.data[dataset.obj]
    })
  },
  clickGetContact: function() {
    // 点击获取价格，联系方式
    let _this = this
    if (_this.data.adopt == false) {
      // 没有授权
      if (_this.data.homePageBottomBtnText == '等待授权中') {
        wx.showToast({
          title: '请耐心等候授权',
          icon: 'none'
        })
      } else if (_this.data.homePageBottomBtnText == '查看价格、联系方式') {
        _this.setData({
          zhezhao: true,
          passwordVerificationWindow: true,
        })
      } else if (_this.data.homePageBottomBtnText == '申请未通过') {
        wx.showModal({
          title: '是否再次申请？',
          success(res) {
            if (res.confirm) {
              _this.setData({
                zhezhao: true,
                passwordVerificationWindow: true,
              })
            } else if (res.cancel) {
              console.log('取消再次申请查看价格')
            }
          }
        })
      }
    } else if (_this.data.adopt == true) {
      // 已经通过授权
      _this.setData({
        contactMsgWindow: true,
        zhezhao: true,
      })
    }
  },
  cancel: function() {
    // 取消授权查看,取消登录密码验证，取消添加标签
    this.setData({
      zhezhao: false,
      shouquanWindow: false,
      passwordVerificationWindow: false,
      contactMsgWindow: false,
      labelWindow: false,
      labelFormWindow: false
    })
  },
  allowLook: function() {
    // 确定授权查看
    // 发送授权查看申请
    let _this = this
    let navId = wx.getStorageSync('navid')
    let userId = wx.getStorageSync('userId')
    let config = wx.getStorageSync('config')
    wx.request({
      url: config.host + 'api/review/addReview',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        isLabel: 1,
        productId: _this.data.productId,
        type: navId,
        userId: userId
      },
      success(res) {
        if (res.statusCode == 200 && res.data.status == 200) {
          wx.showToast({
            title: '已提交申请,等待授权',
            icon: 'none'
          })
        }
      }
    })

    this.setData({
      zhezhao: false,
      shouquanWindow: false,
      homePageBottomBtnText: '等待授权中',
      passwordVerificationWindow: false,
    })
  },
  allowVerification: function() {
    // 登录密码验证-确定
    let _this = this
    let phone = wx.getStorageSync('phone')
    let config = wx.getStorageSync('config')
    wx.request({
      url: config.host + 'api/user/findPassword',
      method: 'POST',
      data: {
        passWord: _this.data.passwordValue,
        userName: phone
      },
      success(res) {
        if (res.data.status == 200 && res.data.msg == 'ok') {
          _this.setData({
            shouquanWindow: true,
            passwordVerificationWindow: false
          })
        } else if (res.data.status == 400) {
          _this.setData({
            zhezhao: false,
            passwordVerificationWindow: false
          })
          wx.showToast({
            title: '密码错误',
            icon: 'none'
          })
        }
      }
    })
  },
  allowAddLabel: function() {
    // 申请添加标签-确定
    this.setData({
      labelWindow: false,
      labelFormWindow: true
    })
  },
  allowAddLabelForm: function() {
    // 添加标签-确定
    let _this = this
    let userId = wx.getStorageSync('userId')
    let navId = wx.getStorageSync('navid')
    let labelValue = this.data.labelValue
    let labelItemCount = this.data.labelItemCount
    let labelItemLength = this.data.labelItemLength
    let labelArr = labelValue.split(/[,，]/)
    let newLabelArr = []
    let flag = false
    let config = wx.getStorageSync('config')
    if (labelArr.length > labelItemCount) {
      // 标签数量超标
      wx.showToast({
        title: '标签数量不得多于' + labelItemCount + '个！',
        icon: 'none'
      })
    } else if (labelArr.length > 0 && labelArr.length <= labelItemCount) {
      // 标签数量合法，判断单个标签字数
      for (let i = 0; i < labelArr.length; i++) {
        if (labelArr[i].length > labelItemLength) {
          wx.showToast({
            title: '单个标签内容不得超过' + labelItemLength + '个字符！',
            icon: 'none'
          })
        } else if (labelArr[i].length > 0 && labelArr[i].length <= labelItemLength) {
          newLabelArr.push(labelArr[i])
          newLabelArr.length == labelArr.length ? flag = true : flag = false
        } else if (labelArr[i].length == 0) {
          wx.showToast({
            title: '不得输入空标签！',
            icon: 'none'
          })
        }
      }
      if (flag) {
        // 单标签总字数合法，提交标签
        _this.setData({
          labelValue: newLabelArr
        })
        _this.setData({
          zhezhao: false,
          labelFormWindow: false
        })
        wx.request({
          url: config.host + 'api/review/addReview',
          method: 'POST',
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          data: {
            isLabel: 0,
            labelName: _this.data.labelValue,
            productId: _this.data.productId,
            type: navId,
            userId: userId
          },
          success(res) {
            if (res.data.status == 200 && res.data.msg == '成功') {
              wx.showToast({
                title: '已提交申请，等待审核',
                icon: 'none'
              })
            }
          }
        })
      }
    } else {
      // 标签栏为空
      wx.showToast({
        title: '请输入标签内容',
        icon: 'none'
      })
    }
  },
  clickEyeIcon: function() {
    this.setData({
      eyeSwitch: !this.data.eyeSwitch
    })
  },
  clickAddLabel: function() {
    // 新增标签
    this.setData({
      zhezhao: true,
      labelWindow: true
    })
  },
  setNavigationTitle: function(name) {
    // 设置页面标题
    wx.setNavigationBarTitle({
      title: name
    })
  },
  onPullDownRefresh: function() {
    // 下拉刷新-判断底部按钮是否审核通过
    // 标题栏显示刷新图标
    wx.showNavigationBarLoading()
    // 请求最新数据

    setTimeout(() => {
      // 标题栏隐藏loading图标
      wx.hideNavigationBarLoading()
    }, 2000)
  },
  findingsOfAudit: function() {
    // 获取审核结果
    let _this = this
    let userId = wx.getStorageSync('userId')
    let config = wx.getStorageSync('config')
    wx.request({
      url: config.host + 'api/product/infoReview',
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        productId: _this.data.productId,
        userId: userId
      },
      success(res) {
        if (res.data.msg == 'ok') {
          // 通过
          _this.setData({
            homePageBottomBtnText: '申请通过',
            adopt: true,
            phone: res.data.data.phone,
            price: res.data.data.insidePrice
          })
        } else if (res.data.msg == '1') {
          // 未通过
          _this.setData({
            homePageBottomBtnText: '申请未通过',
            adopt: false
          })
        } else if (res.data.msg == '2') {
          // 未审核
          _this.setData({
            homePageBottomBtnText: '等待授权中',
            adopt: false
          })
        } else if (res.data.msg == '3') {
          // 没提交过申请
          _this.setData({
            homePageBottomBtnText: '查看价格、联系方式',
            adopt: false
          })
        }
      }
    })
  },
  changeProject: function(e) {
    // 加入项目
    let that = this
    let config = wx.getStorageSync('config')
    let index = e.detail.value
    this.setData({
      projectIdx: index
    })
    let projectId = that.data.projectList[index].id
    wx.request({
      url: config.host + 'api/project/addProjectAgree?projectId=' + projectId,
      method: 'POST',
      data: {
        productId: that.data.productId,
        productName: wx.getStorageSync('name'),
        type: that.data.personMsgList.type
      },
      success(res) {
        if (res.data.status == 400) {
          wx.showToast({
            title: res.data.msg,
            icon: 'none'
          })
        } else if (res.data.status == 200) {
          wx.showToast({
            title: '成功加入项目',
            icon: 'none'
          })
        }
      }
    })
  },
  gotoNewProject: function() {
    // 没有项目-去新建项目
    wx.showModal({
      content: '你还没有新建项目',
      confirmText: '去新建',
      confirmColor: '#117FF2',
      success(res) {
        if (res.confirm) {
          wx.redirectTo({
            url: '/pages/newProject/newProject',
          })
        } else if (res.cancel) {
          console.log('取消新建项目')
        }
      }
    })
  },
  showCalendar: function() {
    // 拉起日期
    this.setData({
      calendarWindow: !this.data.calendarWindow,
      zhezhao: !this.data.zhezhao
    })
  },
  getProjectName: function() {
    // 获取加入项目选项值
    let that = this
    let config = wx.getStorageSync('config')
    wx.request({
      url: config.host + 'api/project/findProjectTwo',
      method: 'GET',
      data: {
        userId: wx.getStorageSync('userId')
      },
      success(res) {
        that.setData({
          projectList: res.data.data
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    let _this = this
    let navid = wx.getStorageSync('navid')
    let config = wx.getStorageSync('config')
    let dataDetailUrl = config.host + 'api/product/info'
    this.setData({
      navId: navid,
      productId: options.id
    })
    wx.request({
      url: dataDetailUrl,
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      data: {
        productId: options.id
      },
      success(res) {
        if (res.data.status == 200 && res.data.msg == 'ok') {
          let data = {}
          let label = res.data.data.label.split(',')
          data = res.data.data
          data.label = label
          _this.setData({
            personMsgList: data
          })
          // 设置日历排期
          _this.calcScheduling()
          // 设置页面标题
          _this.setNavigationTitle(res.data.data.name)
        }
        // 获取授权结果
        _this.findingsOfAudit()
      }
    })
    // 获取加入项目选项值
    _this.getProjectName()
  },
  onShow: function() {

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  }
})